<template>
  <el-dialog v-model="dialogFormVisible" title="Shipping address" width="500">
    <el-form :model="form" :rules="rules">
      <el-form-item
        prop="newPassword"
        :label="$t('pageSessions.modal.newPassword')"
        :label-width="formLabelWidth"
      >
        <el-input v-model="form.newPassword" autocomplete="off" />
      </el-form-item>
      <el-form-item
        prop="confirmPassword"
        :label="$t('pageSessions.modal.confirmPassword')"
        :label-width="formLabelWidth"
      >
        <el-input v-model="form.confirmPassword" autocomplete="off" />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="resetForm">
          {{ $t('global.action.cancel') }}
        </el-button>
        <el-button type="primary" @click="handleSubmit">
          {{ $t('global.action.confirm') }}
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import useVuelidateTool from '@/hooks/useVuelidateTool';

const {
  useVuelidate,
  required,
  minLength,
  maxLength,
  sameAs,
  elementInputValidator,
} = useVuelidateTool();
const formLabelWidth = '80px';
const dialogFormVisible = ref(false);
defineExpose({ dialogFormVisible });

const emit = defineEmits(['ok', 'hidden']);

const props = defineProps<{
  user: Object | undefined;
  passwordRequirements: { minLength: number; maxLength: number };
}>();

const form = reactive({
  newPassword: '',
  confirmPassword: '',
});

const newpassword = toRef(form, 'newPassword');

const v$ = useVuelidate(
  {
    newPassword: {
      required,
      minLength: minLength(props.passwordRequirements.minLength),
      maxLength: maxLength(props.passwordRequirements.maxLength),
    },
    confirmPassword: {
      required,
      minLength: minLength(props.passwordRequirements.minLength),
      maxLength: maxLength(props.passwordRequirements.maxLength),
      confirmPassword: sameAs(newpassword),
    },
  },
  form,
);

const rules = computed(() => {
  return {
    newPassword: [
      {
        trigger: 'change',
        validator: elementInputValidator.value(v$, 'newPassword'),
      },
    ],
    confirmPassword: [
      {
        trigger: 'change',
        validator: elementInputValidator.value(v$, 'confirmPassword'),
      },
    ],
  };
});

const closeModal = () => {
  nextTick(() => {
    dialogFormVisible.value = false;
    form.newPassword = '';
    form.confirmPassword = '';
    v$.value.$reset();
  });
};
const resetForm = () => {
  form.newPassword = '';
  form.confirmPassword = '';
  closeModal();
  v$.value.$reset();
};

const handleSubmit = () => {
  v$.value.$touch();
  if (v$.value.$invalid) return;
  closeModal();
  emit('ok', form.confirmPassword);
};
</script>
